package org.langqiao.xml;


import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class XmlTest {
	public static void main(String [] args){
	    //Logger log = LoggerFactory.getLogger(XmlTest.class);
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		try
		{
			DocumentBuilder db = dbf.newDocumentBuilder();
			org.w3c.dom.Document doc = db.parse("test.xml");
			NodeList testList = doc.getElementsByTagName("dog");
			System.out.println("文档中共有"+testList.getLength()+"条狗");
			for(int i=0;i<testList.getLength();i++)
			{
				Node dog = testList.item(i); //获取第i个元素的信息
				Element ele = (Element)dog;
				String attValue = ele.getAttribute("id");
				System.out.println("id 属性值是："+attValue);
				//循环读取该子节点下的所有节点
				for(Node node = dog.getFirstChild();node!=null;node=node.getNextSibling())
				{
					if(node.getNodeType()==Node.ELEMENT_NODE)
					{
						String name = node.getNodeName();
						String value = node.getFirstChild().getNodeValue();//元素节点的子节点是内容节点
						System.out.println(name+":"+value);
					}
				 } 
			 }
		 }
		catch (Exception e) {
			
		}
	}

}
